import Vue from 'vue'

Vue.prototype.$dates = function(week, date, reg) {
  let [yyyy, mm] = date
    .toString()
    .split(reg || '-')
    .map((item) => parseInt(item))

  if (isNaN(yyyy)) new Error('日期年份格式错误！')

  if (isNaN(mm)) {
    let result = []
    for (let m = 1; m <= 12; m++) {
      result.push(this.$dates(week, `${yyyy}-${m < 10 ? '0' + m : m}`))
    }
    return result.flat()
  } else {
    let days = 31

    if (mm < 1 || mm > 12) throw new Error('日期月份格式错误！')
    if (mm === 2)
      days = (yyyy % 4 === 0 && yyyy % 100 !== 0) || yyyy % 400 === 0 ? 29 : 28
    if (mm === 4 || mm === 6 || mm === 9 || mm === 11) days = 30

    let dates = []

    for (let i = 1; i <= days; i++) {
      dates.push(new Date(`${yyyy}-${mm}-${i} 12:00:00`))
    }

    let filters = dates.filter((d) => week % 7 === d.getDay())

    return filters.map(
      (d) =>
        `${yyyy}-${mm < 10 ? '0' + mm : mm}-${
          d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
        }`
    )
  }
}
